<template>
  <div>
    <CrumBsofbread name1="商品管理" name2="商品分类" />

    <el-card>
      <el-row>
        <el-button type="primary" @click="buttonPji">添加分类</el-button>
      </el-row>
      <tree-table class="treeTable" :data="catelist" :columns="columns" :selection-type="false" 
      :expand-type="false" show-index index-text="序号" border>
        <template slot="isok" slot-scope="scope">
          <i class="el-icon-success" v-if="scope.row.cat_deleted === false" style="color: lightgreen"></i>
          <i class="el-icon-error" v-else style="color: red"></i>
        </template>
        <!-- 排序 -->
        <template slot="order" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag size="mini" type="success" v-else-if="(scope.row.cat_level === 1)">二级</el-tag>
          <el-tag size="mini" type="warning" v-else>三级</el-tag>
        </template>
        <!-- 操作 -->
        <template slot="opt" slot-scope="scope">
          <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeUser(scope.row.cat_id)">删除</el-button>
        </template>
      </tree-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="querInfo.pagenum"
        :page-sizes="[3, 5, 10, 15]"
        :page-size="querInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    <!-- 添加分类对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="addCateDialogClosed">
      <el-form :model="addCateForm" :rules="addCateFormRules" ref="addCateFormRef" label-width="100px">
        <el-form-item label="分类名称：" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="商品名称：">
          <!-- options数据  :props="cascaderProps"旧版 -->
          <!-- cascaderProps 指定配置对象 -->
          <el-cascader
            expand-trigger="hover"          
            :options="parentCateList"
            :props="{ expandTrigger: 'hover', ...cascaderProps, checkStrictly: 'true'}"
            
            v-model="selectedkeys"
            @change="parentCateChanged" 
            clearable>
          </el-cascader>
        </el-form-item>
       </el-form> 
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑对话框 -->
    <el-dialog
      title="编辑分类"
      :visible.sync="editDialogVisible"
      width="50%">
      <el-form :model="editCate" :rules="editFormRules" ref="editFormRef" label-width="80px">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editCate.cat_name"></el-input>
        </el-form-item>
       </el-form> 
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import CrumBsofbread from '../CrumBsofbread.vue'
export default {
  components: {
    CrumBsofbread,
  },
  data() {
    return {
      querInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      //商品分类数据
      catelist: [],
      //总数据条数
      total: 0,
      //为table指定列
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name'
        },
        {
          label: '是否有效',
          //当列定义为前模板列
          type: 'template',
          //当列这一列使用模板名称
          template: 'isok'
        },
        {
          label: '排序',
          //当列定义为前模板列
          type: 'template',
          //当列这一列使用模板名称
          template: 'order'
        },
        {
          label: '操作',
          //当列定义为前模板列
          type: 'template',
          //当列这一列使用模板名称
          template: 'opt'
        }
      ],
      //控制添加分类对话框显示与隐藏
      setRightDialogVisible: false,
      //添加分类的表单数据对象
      addCateForm: {
        //添加分类的名称
        cat_name: '',
        //父级分类id
        cat_pid: '',
        //分类等级 默认1级
        cat_level: 0
      },
      //添加分类表单验证规则
      addCateFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur'}
        ]
      },
      //父级分类列表
      parentCateList: [],
      //指定级联选择器的配置对象
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      //选中的父级分类id数组
      selectedkeys: [],
      //控制编辑分类对话框显示与隐藏
      editDialogVisible: false,
      //编辑分类名称数据
      editCate: {},
      editCateId: ''
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    //获取商品分类数据
    async getCateList() {
      const { data: res } = await this.$http.get('categories', {params: this.querInfo})
      if (res.meta.status !== 200) {
        return this.$message.error("获取商品分类失败！")
      }
      console.log(res.data);
      //数据列表 赋值给catelist
      this.catelist = res.data.result
      //为总数据条数赋值
      this.total = res.data.total
    },
    //监听 pagesize 改变
    handleSizeChange(newSize) {
      this.querInfo.pagesize = newSize
      this.getCateList()
    },
    //监听 pagenum 改变
    handleCurrentChange(newPage) {
      this.querInfo.pagenum = newPage
      this.getCateList()
    },
    //添加分类按钮
    buttonPji() {
      this.getParentCateList()
      this.setRightDialogVisible = true
    },
    //获取父级分类得到数据
    async getParentCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 2}
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取父级数据失败！')
      }
      this.parentCateList = res.data
      //console.log(res.data);
    },
    //选择项发生变化触发这个函数
    parentCateChanged() {
      if (this.selectedkeys.length > 0) {
        //父级分类id
        this.addCateForm.cat_pid = this.selectedkeys[this.selectedkeys.length -1]
        //为当前分类的等级赋值
        this.addCateForm.cat_level = this.selectedkeys.length
        return
      } else {
        //父级分类id
        this.addCateForm.cat_pid = 0
        //当前分类的等级赋值
        this.addCateForm.cat_level = 0
      }
    },
    //点击对话框关闭按钮
    addCate() {
      this.$refs.addCateFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('categories', this.addCateForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加分类失败！')
        }
        this.$message.success('添加分类成功')
        this.getCateList()
        this.setRightDialogVisible = false
      })
    },
    //关闭对话框 清空数据
    addCateDialogClosed() {
      this.$refs.addCateFormRef.resetFields()
      this.selectedkeys = []
      this.addCateForm.cat_level = 0
      this.addCateForm.cat_pid = 0
    },
    //编辑分类对话框
    async showEdit(cateInfo) {
      this.editCateId = cateInfo.cat_id
      //发生请求获取数据
      const { data: res } = await this.$http.get('categories/' + cateInfo.cat_id)
      this.editCate = res.data
      this.editDialogVisible = true
    },
    //编辑分类并提交
    async editUser() {
      const { data: res } = await this.$http.put('categories/' + 
      this.editCate.cat_id, {cat_name: this.editCate.cat_name})
      if (res.meta.status !== 200) {
        return this.$message.error('编辑失败！')
      }
      this.$message.success('编辑成功')     
      //关闭对话框
      this.editDialogVisible = false
      //重新获取数据
      this.getCateList()
    },
    //删除分类
    async removeUser(id) {
      //弹出确定取消框，是否删除用户
      const confirmResult = await this.$confirm(
        "请问是否要永久删除该用户",
        "删除提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);

      if (confirmResult != "confirm") {
        return this.$message.info("已经取消删除");
      }
      //发送请求根据id完成删除操作
      const { data: res } = await this.$http.delete("categories/" + id);
      if (res.meta.status !== 200) return this.$message.error("删除分类失败! ");
      this.$message.success("删除分类成功");
      console.log(res.data);
      //重新请求最新的数据
      this.getCateList();
    }
  }
}
</script>

<style lang="less" scoped>
  .treeTable {
    margin-top: 15px;
  }
  .el-cascader {
    width: 100%;
  }
</style>